#coding=utf-8
from storm.locals import *
from db import *
import wx.lib.pubsub as ps
mainFrame = None

database = create_database('mysql://ad:ad@localhost/adwords')
store = Store(database)

current_user_name = u'jay'
current_user = store.find(User, User.name==current_user_name).one()
current_camp = store.find(Campaign, Campaign.user_id==User.id, User.name==u'jay').\
        order_by(Desc(Campaign.last_modified_at)).first()
        
current_ad = None

camp_tree = []

def generate_camp_tree():
    global camp_tree
    camp_tree = []
    r = store.find(Campaign, Campaign.user_id==User.id, User.name==u'jay').\
        order_by(Desc(Campaign.last_modified_at))
    
    for c in r:
        a = []
        for ad in c.ads:
            a.append(ad.name)
        if a:camp_tree.append([c.name, a])
        else:
            camp_tree.append(c.name)
        
    return camp_tree
    
def set_current_user():
    global current_user
    current_user = store.find(User, User.name==u'jay').one()
    #return current_user

def set_current_camp():
    global current_camp
    camp = store.find(Campaign, Campaign.user_id==User.id, User.name==u'jay').\
        order_by(Campaign.last_modified_at).first()
    #return current_camp
        
def start_up():
    global current_user
    
    if not current_user:
        u = User()
        u.name = u'jay'
        store.add(u)
        store.flush()
        
        set_current_user()
        
    
      
            
    
